package com.mxf.code.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = {"com.mxf.code.mapper.dynamic02"},
        sqlSessionFactoryRef = "dynamic02SqlSessionFactory")
public class Dynamic02DatasourceConfig {

    @Bean("dynamic02DatasourceProperties")
    @ConfigurationProperties(prefix = "dynamic-datasource.dynamic02")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    @Primary
    @Bean("dynamic02Datasource")
    public DataSource dataSource(@Qualifier("dynamic02DatasourceProperties") DataSourceProperties properties) {
        return DataSourceBuilder.create()
                .driverClassName(properties.getDriverClassName())
                .url(properties.getUrl())
                .username(properties.getUsername())
                .password(properties.getPassword())
                .build();
    }

    @Primary
    @Bean(name = "dynamic02TransactionManager")
    public PlatformTransactionManager dataSourceTransactionManager(@Qualifier("dynamic02Datasource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "dynamic02SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamic02Datasource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setTypeHandlersPackage("com.mxf.code.entity.dynamic02");
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/dynamic02/*.xml"));
        return sessionFactoryBean.getObject();
    }

    @Primary
    @Bean(name = "dynamic02SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("dynamic02SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}